package thread;
//模拟实现简单的阻塞队列，模拟生产者消费者模型
class MyBlockingQueue{
    private String[] Data = null;
    private int head = 0;
    private int tail = 0;
    private int size = 0;

    public MyBlockingQueue(int capacity){
        Data = new String[capacity];
    }

    public void put(String elem) throws InterruptedException {
        synchronized (this){
            while(size >= Data.length){
                this.wait();
            }
            Data[tail] = elem;
            tail++;
            if(tail >= Data.length){
                tail = 0;
            }
            size++;
            this.notify();
        }
    }

    public String take() throws InterruptedException {
     synchronized (this){
         while(size == 0){
             this.wait();
         }
         String ret = Data[head];
         head++;
         if(head >= Data.length){
             head = 0;
         }
         size--;
         this.notify();
         return ret;
     }
    }
}

public class parctice6 {
    public static void main(String[] args) {
        MyBlockingQueue queue = new MyBlockingQueue(1000);
        Thread producer = new Thread(()->{
            int n = 0;
            while(true){
                try {
                    queue.put(n+"");
                    System.out.println("生产者生产"+n);
                    n++;
                } catch (InterruptedException e) {
                    e.printStackTrace();
                }
            }
        });

        Thread consumer = new Thread(()->{
            while(true){
                try {
                    String ret = queue.take();
                    System.out.println("消费者消费"+ret);
                    Thread.sleep(1000);
                } catch (InterruptedException e) {
                    e.printStackTrace();
                }
            }
        });

        producer.start();
        consumer.start();
    }
}
